// axios二次封装
import axios from 'axios'
import enConfig from './env'
import { Toast } from 'vant'
import router from '../router/index'
// 创建axios实例
const service = axios.create({
  // 设置基地址
  baseURL: enConfig.port.baseURL,
  timeout: 5000
})

// 创建请求拦截器
service.interceptors.request.use(
  (config) => {
    let a = JSON.parse(localStorage.getItem('counter')) || []
    let token = a.res.remember_token
    console.log(config.status)
    if (!token && config.status) {
      router.push('/login')
    } else {
      config.headers.zywxtoken = 'zywx' + a.res?.remember_token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 创建响应拦截器
service.interceptors.response.use(
  (res) => {
    console.log('res:::', res)
    const { msg, code, data: result } = res.data
    const successCodeArr = [200]
    if (successCodeArr.includes(code)) {
      Toast.success(msg)
      return result
    }
    Toast.fail(msg)
    return Promise.reject(msg)
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
